<?php

namespace App\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Admin extends Controller
{
    //
    public function index(){
        // 自定义的lists 方法
        $res= DB::table('admin')->lists();
        // $res = DB::table('admin')->get()->all();
        $data['list']=$res;
        foreach($data['list'] as $key=>$val){
            $onerole=DB::table('admin_group')->where('gid',$data['list'][$key]['gid'])->first();
            $data['list'][$key]['role_name']=$onerole->title;
        }
        return view("admins\admin.index" ,$data);
    }
    /**
     * 点击新增管理员
     */
    public function add(){
        $res=DB::table('admin_group')->lists();
        $data["groups"]=$res;
        return view("admins\admin.add",$data);
    }
    /***
     * 点击保存管理员
     */
    public function save(Request $request){

        $data['real_name']= trim($request->uname);
        $data['password']=trim($request->pwd);
        $data['username']=trim($request->username);
        $data['status']=$request->status ==="on"?0:1;
        $data['gid']=(int)trim($request->role_title);

        if($data['username']==""){
            exit(json_encode(['code'=>1,'msg'=>'用户名不能为空']));
        }
        $res= DB::table('admin')->where('username',$data['username'])->first();
        if($res){
           exit(json_encode(['code'=>1,'msg'=>'当前用户名已存在']));
        }
        // 保存到数据库
        $data['password']= password_hash($data['password'],PASSWORD_DEFAULT);

        $res=DB::table('admin')->insert($data);
        if($res){
            dd($res);
        }
    }
}
